package com.tcm.smarthealth.controller;

import com.tcm.smarthealth.common.ApiResponse;
import com.tcm.smarthealth.common.exception.BusinessException;
import com.tcm.smarthealth.dto.QuestionCreateRequest;
import com.tcm.smarthealth.dto.QuestionResponse;
import com.tcm.smarthealth.dto.QuestionStreamChunk;
import com.tcm.smarthealth.enums.QuestionType;
import com.tcm.smarthealth.security.AuthContext;
import com.tcm.smarthealth.security.AuthenticatedUser;
import com.tcm.smarthealth.service.QuestionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.codec.ServerSentEvent;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import javax.validation.Valid;
import java.util.List;

@Tag(name = "智能问答", description = "中医/西医/中西结合问答接口")
@RestController
@RequestMapping("/api/v1/questions")
@Validated
public class QuestionController {

    private final QuestionService questionService;

    public QuestionController(QuestionService questionService) {
        this.questionService = questionService;
    }

    @Operation(summary = "提交问题并获取智能回答")
    @PostMapping
    public Mono<ApiResponse<QuestionResponse>> createQuestion(@Valid @RequestBody QuestionCreateRequest request) {
        AuthenticatedUser currentUser = ensureAuthenticated();
        return Mono.fromCallable(() -> questionService.createQuestion(request, currentUser.getId()))
                .subscribeOn(Schedulers.boundedElastic())
                .map(ApiResponse::success);
    }

    @Operation(summary = "流式获取智能回答")
    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<QuestionStreamChunk>> streamQuestion(@Valid @RequestBody QuestionCreateRequest request) {
        AuthenticatedUser currentUser = ensureAuthenticated();
        return questionService.streamQuestion(request, currentUser.getId())
                .map(chunk -> ServerSentEvent.<QuestionStreamChunk>builder()
                        .id(String.valueOf(System.nanoTime()))
                        .event("message")
                        .data(chunk)
                        .build());
    }

    @Operation(summary = "查询问答记录")
    @GetMapping
    public ApiResponse<List<QuestionResponse>> listQuestions(
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        AuthenticatedUser currentUser = ensureAuthenticated();
        QuestionType questionType = type != null && !type.isBlank() ? QuestionType.fromCode(type) : null;
        List<QuestionResponse> responses = questionService.listQuestions(currentUser.getId(), questionType, page, size);
        return ApiResponse.success(responses);
    }

    private AuthenticatedUser ensureAuthenticated() {
        AuthenticatedUser user = AuthContext.getCurrentUser();
        if (user == null) {
            throw new BusinessException(HttpStatus.UNAUTHORIZED, "登录已失效，请重新登录");
        }
        return user;
    }
}

